// JavaScript methods for retrieving email template (FreeMarker template) using a web call.
// Author: Mike Moore
function findEmailTemplateText(contextRoot, user, domainId, pcode, templateId) {
	log('EmailTemplate.findEmailTemplateText() called - context = ' + contextRoot);
	document.getElementById("templateText").value = '';
	var href = contextRoot + '/ws?command=get.email.template&user='
	     + user +  '&domainId=' + domainId + '&pcode=' + pcode + '&templateId=' + templateId;
	log('EmailTemplate.findEmailTemplateText() - href 1: ' + href);
	remoteCall(href, handleXmlTemplateResponse, templateRemoteCallError);
}
 
 // Callback for errors during remote calls.
 function templateRemoteCallError(href) {
 	alert('An error occurred attempting to contact the remote server.  Data call: ' + href);
 }

function handleXmlTemplateResponse() {
  // if the readyState code is 4 (Completed)
  // and http status is 200 (OK) we go ahead and get the responseText
  // other readyState codes:
  // 0=Uninitialized 1=Loading 2=Loaded 3=Interactive
  log("Response received from server, processing XML response.");
  var xmlhttp = getXmlHttp();
  if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
				xmlDoc =
					AjxXmlDoc.createFromXml(xmlhttp.responseText);

				nativeDocument = xmlDoc.getDoc();
				templateNodes = nativeDocument.getElementsByTagName("emailTemplate");
				displayTemplateNode(templateNodes);
				log('EmailTemplate.handleXmlTemplateResponse() - done displaying template node');
		} else {
			log("Not processed - Response status = " + xmlhttp.status);
		}
  } else {
		log("Not processed - Response readyState = " + xmlhttp.readyState);
		if (xmlhttp.readyState == 3)
			document.getElementById("templateText").value = 'Error - lost connection with server';
  }
}


function displayTemplateNode(currentTemplateNodes) {
	log('EmailTemplate.displayTemplateNode(currentTemplateNodes) called - node count: ' + currentTemplateNodes.length);
	var text = '';
	var subject = '';
	if (currentTemplateNodes.length > 0) {
		node = currentTemplateNodes[0];
		text = node.getAttribute("text");
		subject = node.getAttribute("subject");
		subject = decodeLineFeeds(subject);
		text = decodeLineFeeds(text);
		//alert("Template Text: " + textStr);
	    log('EmailTemplate.displayTemplateNode() - received template node,   id = ' + node.getAttribute('id'));
    }
	displayTemplateText(text, subject);
}

function displayTemplateText(newText, subject) {
	log('EmailTemplate.displayTemplateText() - newText = ' + newText);
	var templateTextControl = document.getElementById("templateText");
	log('EmailTemplate.displayTemplateText() - have reference to text area');
	templateTextControl.value = newText;
	log('EmailTemplate.displayTemplateText() - finished');

	var templateSubjectControl = document.getElementById("subject");
	templateSubjectControl.value = subject;
}

